package com.cloudeye.logtest.netty;

import com.sun.javafx.util.Logging;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * Created by lafangyuan on 2021/1/4.
 */
@Slf4j
public class WebSocketServer {

    public void run() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup worker = new NioEventLoopGroup();
        EventLoopGroup server = new NioEventLoopGroup();
        serverBootstrap.group(server,worker)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast(new ChunkedWriteHandler())
                                .addLast(new HttpObjectAggregator(65536))
//                                .addLast(new WebSocketServerCompressionHandler())
                                .addLast(new WebSocketServerProtocolHandler("/ws",null,true))
                                .addLast(new WebSockertMonitorHandler());
                    }
                });
        ChannelFuture sync = serverBootstrap.bind(8888).sync();
        sync.channel().closeFuture().sync();
    }

    class WebSockertMonitorHandler extends SimpleChannelInboundHandler<Object>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            log.info("{}:{}",ctx.channel().id(),msg.toString());
            //握手调用，已在WebSocketServerProtocolHandler中实现
            if(msg instanceof FullHttpRequest){
            }
            if(msg instanceof TextWebSocketFrame){
                TextWebSocketFrame webSocketMsg = (TextWebSocketFrame) msg;
                String text = webSocketMsg.text();
                log.info("received web socket msg: {}",text);
                ctx.writeAndFlush(new TextWebSocketFrame("当前时间："+ LocalDateTime.now()));
            }

        }
    }

    private void handlerHttpRequest(ChannelHandlerContext ctx, FullHttpRequest msg) {

    }

    public static void main(String[] args) throws InterruptedException {
        new WebSocketServer().run();
    }
}
